const Mock = require('mockjs');
const http = require('http');
const moment = require('moment');

const { mock } = Mock;

let interval;
http
  .createServer(function(req, res) {
    const fileName = `.${req.url}`;
    if (fileName === './stream') {
      res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        'Access-Control-Allow-Origin': '*',
      });
      res.write('retry: 10000\n');
      res.write('event: connecttime\n');
      res.write(`data: ${new Date().toDateString()}\n\n`);

      interval = setInterval(function() {
        res.write('retry: 10000\n');
        const data = {
          key: mock('@id'),
          title: mock('@ctitle'),
          content: mock('@cparagraph'),
          createTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        };
        res.write(`data: ${JSON.stringify(data)} \n\n`);
      }, 4000);

      req.connection.addListener(
        'close',
        function() {
          clearInterval(interval);
        },
        false,
      );
    }
  })
  .listen(8844, '127.0.0.1');
